/**
 * author:Administrator
 * date:2013-5-21
 */
package com.roc.web.action.setting;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.dao.IBaseDao;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction; // import com.roc.pojo.Merchant;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.Operators;
import com.roc.pojo.SettingBean; // import com.roc.pojo.ProfitRule;
import com.roc.pojo.SettingItemBean;
import com.roc.service.IPagenitionService; // import
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.setting.ISettflagService;
import com.roc.util.Constance;
import com.roc.util.constant.AuditingResultCodeType;
import com.roc.util.constant.AuditingType;
import com.roc.util.constant.Constant;
import com.roc.util.constant.SysLogType;

/**
 * @author Feng haitao
 * 
 */
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/setting")
public class ReviewSettingAction extends PaginationBaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5236170890634487270L;
	private Logger logger = LogManager.getLogger(ReviewSettingAction.class);
	private Operators operators;
	private ReviewSettingSearchCondition searchCondition;
	private String idd;
	private String msg;
	private SettingBean sett;
	private AuditingItem auditing;

	@Autowired
	IPagenitionService pagenitionService;

	@Autowired
	IorgService orgService;
	@Autowired
	ISettflagService settflagService;

	// 审核查询
	@Action(value = "reviewsettingsearch", results = {
			@Result(name = "success", location = "/pages/setting/reviewsettinglist.jsp"),
			@Result(name = "error", location = "/pages/setting/frozenlist.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp") })
	public String reviewsettingsearch() {
		Operators logingMerchant = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		Map<String, Operators> merchantMap = new TreeMap<String, Operators>();
		if (searchCondition == null) {
			searchCondition = (ReviewSettingSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new ReviewSettingSearchCondition();
			}
		}
		try {
			// 系统管理员查看全部，代理只能看到本机构下的。
			// if (Constance.MERCHANT_TYPE_DAILI.equals(logingMerchant
			// .getRoleType())) {
			// searchCondition.setOrgCode(logingMerchant.getOrgCode());
			// }

			double sum = settflagService.querySummoney(searchCondition);
			int rows = pagenitionService.countSQL(searchCondition);
			List<SettingBean> settingList = new ArrayList<SettingBean>();
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				if (searchRsList != null && searchRsList.size() > 0) {
					Iterator iterator = searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();
						SettingBean sett = new SettingBean();
						if (obj[0] != null && !"".equals(obj[0])) {
							sett.setOrderno(obj[0].toString());
						}
						if (obj[1] != null && !"".equals(obj[1])) {
							sett.setMerchantno(obj[1].toString());
						}
						if (obj[2] != null && !"".equals(obj[2])) {
							sett.setMerchantname(obj[2].toString());
						}
						if (obj[3] != null && !"".equals(obj[3])) {
							sett.setSettledate(obj[3].toString());
						}
						if (obj[4] != null && !"".equals(obj[4])) {
							sett.setFreezeflag(obj[4].toString());
						}
						if (obj[5] != null && !"".equals(obj[5])) {
							sett.setTotalamt(Double.valueOf(obj[5].toString()));
						}
						if (obj[6] != null && !"".equals(obj[6])) {
							sett
									.setTotalnum(Integer.valueOf(obj[6]
											.toString()));
						}
						if (obj[7] != null && !"".equals(obj[7])) {
							sett.setMerchantfee(Double.valueOf(obj[7]
									.toString()));
						}
						if (obj[8] != null && !"".equals(obj[8])) {
							sett.setMerchantsettleamt(Double.valueOf(obj[8]
									.toString()));
						}
						if (obj[9] != null && !"".equals(obj[9])) {
							sett.setSettleflag(obj[9].toString());
						}
						if (obj[10] != null && !"".equals(obj[10])) {
							sett.setBatchno(obj[10].toString());
						}
						if (obj[11] != null && !"".equals(obj[11])) {
							sett.setId(Long.valueOf(obj[11].toString()));
						}
						if (obj[12] != null && !"".equals(obj[12])) {
							sett.setBankdeposit(obj[12].toString());
						}
						if (obj[13] != null && !"".equals(obj[13])) {
							sett.setAccountname(obj[13].toString());
						}
						if (obj[14] != null && !"".equals(obj[14])) {
							sett.setAccountno(obj[14].toString());
						}
						settingList.add(sett);
					}
				}
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute("settingList", settingList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			// getRequest().setAttribute("sum", sum);
			// getRequest().setAttribute("count", rows);
			addActionMessage("当前条件下待结算总金额【" + sum + "】元，待审核总笔数【" + rows + "】");
			setSearchToConditionSession(searchCondition);

		} catch (ServiceException e) {

			logger.error(e.getMessage(), e);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);

		}
		return SUCCESS;
	}

	// 结算审核页面
	@Action(value = "reviewsettinglist", results = {
			@Result(name = "success", location = "/pages/setting/reviewsettinglist.jsp"),
			@Result(name = "login", location = "/pages/redirect.jsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String reviewsettinglist() throws Exception {
		// List settingflagList=new ArrayList();
		// settingflagList=settflagService.querySettingFlagList();
		// getRequest().setAttribute("settingflagList", settingflagList);
		double sum = 0;
		int rows = 0;
		getRequest().setAttribute("sum", sum);
		getRequest().setAttribute("count", rows);
		 List<Object> searchRsList=new ArrayList<Object>() ;
		 System.out.println(searchRsList.size());
		 getRequest().setAttribute("searchRsList", searchRsList);
		return SUCCESS;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (ReviewSettingSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_BEAN_REVIEWSETTING);
	}

	@Action(value = "frozenapply", results = { @Result(name = "success", location = "/pages/setting/frozenapply.jsp") })
	// 查询结算详细信息
	public String frozenapply() {

		// List<SettingBean> settingList=
		// (List<SettingBean>)getSession().getAttribute("settingList");
		// for(int i=0;i<settingList.size();i++){
		// SettingBean SettingBean = settingList.get(i);
		// if(Long.valueOf(idd)==SettingBean.getId()){
		// sett = SettingBean;
		// }
		// }
		try {
			sett = settflagService.querySettingBean(idd);
			Map auditingMap = new HashMap();
			auditingMap.put(AuditingResultCodeType.FREEZEAPPLY.getCode(),
					AuditingResultCodeType.FREEZEAPPLY.getName());
			getRequest().setAttribute("auditingMap", auditingMap);
			getRequest().setAttribute("sett", sett);
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}

	@Action(value = "reviewsettingdate", results = { @Result(name = "success", location = "/pages/setting/reviewsettinglist.jsp") })
	// 结算审核
	public String reviewsettingdate() throws Exception {
		Operators logingMerchant = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);

		try {
			List<Long> iddlist = this.getMulti_sel();
			int n = settflagService.queryStatusCount(iddlist);
			if (n != iddlist.size()) {
				addActionMessage("选择记录" + iddlist.size() + "条，可审核的记录" + n
						+ "条,请重新选择。");
				return reviewsettingsearch();
			}
			for (int i = 0; i < iddlist.size(); i++) {
				String idd = String.valueOf(iddlist.get(i));
				AuditingItem auditing = new AuditingItem();
				// 编辑申请信息入表
				auditing.setAudit_code(AuditingType.SETTING_REVIEWSETTING
						.getCode());
				auditing.setAudit_name(AuditingType.SETTING_REVIEWSETTING
						.getName());
				auditing.setObj_Audited(idd);
				auditing.setOperators(logingMerchant.getAccountNo());

				sett = settflagService.querySettingBean(idd);
				String stuts = "";

				sett.setSettleflag(AuditingResultCodeType.REVIEWSETTING
						.getCode());
				stuts = AuditingResultCodeType.REVIEWSETTING.getCode();

				List<SettingItemBean> list = getsettingitemlist(sett);
				if (list.size() > 0) {
					boolean b = settflagService.reviewsetting(auditing, sett,
							stuts, list);
					if (b) {
						addActionMessage("商户号【" + sett.getMerchantno()
								+ "】结算审核成功");
					} else {
						addActionMessage("商户号【" + sett.getMerchantno()
								+ "】结算审核失败");
					}
				}

				logger.info("------------------------------操作员【"
						+ logingMerchant.getAccountNo() + "】结算审核【" + idd
						+ "】成功！-----------------------------------");

			}
		} catch (ServiceException e) {
			logger.info("------------------------------操作员【"
					+ logingMerchant.getAccountNo() + "】申请冻结【" + idd
					+ "】失败！-----------------------------------");
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return reviewsettingsearch();
	}

	@Action(value = "reviewAllsettingdate", results = { @Result(name = "success", location = "/pages/setting/reviewsettinglist.jsp") })
	// 结算审核全部
	public String reviewAllsettingdate() throws Exception {
		Operators logingMerchant = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		if (searchCondition == null) {
			searchCondition = (ReviewSettingSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new ReviewSettingSearchCondition();
			}
		}
		try {
			int rows = pagenitionService.countSQL(searchCondition);
			List<SettingBean> settingList = new ArrayList<SettingBean>();
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), rows);
				if (searchRsList != null && searchRsList.size() > 0) {
					Iterator iterator = searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();

						String idd = String.valueOf(obj[11].toString());
						AuditingItem auditing = new AuditingItem();
						// 编辑申请信息入表
						auditing
								.setAudit_code(AuditingType.SETTING_REVIEWSETTING
										.getCode());
						auditing
								.setAudit_name(AuditingType.SETTING_REVIEWSETTING
										.getName());
						auditing.setObj_Audited(idd);
						auditing.setOperators(logingMerchant.getAccountNo());

						sett = settflagService.querySettingBean(idd);
						String stuts = "";

						sett.setSettleflag(AuditingResultCodeType.REVIEWSETTING
								.getCode());
						stuts = AuditingResultCodeType.REVIEWSETTING.getCode();

						List<SettingItemBean> list = getsettingitemlist(sett);
						if (list.size() > 0) {
							boolean b = settflagService.reviewsetting(auditing,
									sett, stuts, list);
							if (b) {
								addActionMessage("商户号【" + sett.getMerchantno()
										+ "】结算审核成功");
							} else {
								addActionMessage("商户号【" + sett.getMerchantno()
										+ "】结算审核失败");
							}
						}

						logger.info("------------------------------操作员【"
								+ logingMerchant.getAccountNo() + "】结算审核【"
								+ idd
								+ "】成功！-----------------------------------");
					}
				}
			}
		} catch (ServiceException e) {
			logger.info("------------------------------操作员【"
					+ logingMerchant.getAccountNo() + "】申请冻结【" + idd
					+ "】失败！-----------------------------------");
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return reviewsettingsearch();
	}

	public List<SettingItemBean> getsettingitemlist(SettingBean sett)
			throws Exception {
		List<SettingItemBean> list = new ArrayList<SettingItemBean>();
		int id = 0;
		String str;
		String st = "1";
		try {
			String time = "";
			Date dt = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			time = sdf.format(dt);
			str = settflagService.maxserid(time);
			if (!"1".equals(str)) {
				st = str.substring(1, 6);
			}
			id = Integer.valueOf(st);
			if (id == 99999) {
				id = 1;
			}
			// 收款表中以分为单位。所以要*100.
			Double d = (double) Math.round(Double.parseDouble(String
					.valueOf(sett.getMerchantsettleamt())) * 100 * 100) / 100;

			if (d > 5000000) {
				int k = (int) (d / 5000000);
				for (int m = 0; m <= k; m++) {
					id++;
					SettingItemBean settitem = new SettingItemBean();
					// 当id=99999时重新置成1
					if (id == 99999) {
						id = 1;
					}
					String src = "0000" + id;
					src = src.substring(src.length() - 5);
					String serial = "S" + src;
					settitem.setSerial(serial);
					settitem.setAccountname(sett.getAccountname());
					settitem.setAccountno(sett.getAccountno());
					settitem.setBankname(sett.getBankdeposit());
					settitem.setBanklinkno(sett.getDeposino());
					settitem.setRemark("收单出款");
					settitem.setDelval("0");
					
					settitem.setSettledate(time);
					settitem.setMerchantno(sett.getMerchantno());
					// java.sql.Date date=new java.sql.Date(new
					// java.util.Date().getTime());
					Date date = new Date();
					settitem.setSystime(date);
					settitem.setSettid(sett.getId());
					settitem.setStatus("D");
					if (m != k) {
						settitem.setAmt("5000000");
					} else {
						double t = (double) Math.round((d - m * 5000000) * 100) / 100;
						String amt = String.valueOf(t);
						amt = amt.substring(0, amt.indexOf("."));
						settitem.setAmt(amt);
					}

					list.add(settitem);
				}

			} else {
				SettingItemBean settitem = new SettingItemBean();

				String amt = String.valueOf(d);
				amt = amt.substring(0, amt.indexOf("."));
				id++;
				String src = "0000" + id;
				src = src.substring(src.length() - 5);
				String serial = "S" + src;
				settitem.setSerial(serial);
				settitem.setAccountname(sett.getAccountname());
				settitem.setAccountno(sett.getAccountno());
				settitem.setBankname(sett.getBankdeposit());
				settitem.setBanklinkno(sett.getDeposino());
				settitem.setRemark("收单出款");
				settitem.setAmt(amt);
				settitem.setDelval("0");
				settitem.setStatus("D");
				
				settitem.setSettledate(time);
				settitem.setMerchantno(sett.getMerchantno());
				Date date = new Date();
				settitem.setSystime(date);
				settitem.setSettid(sett.getId());
				list.add(settitem);
			}

		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return list;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc.page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_REVIEWSETTING,
				searchCondition);
	}

	/**
	 * @return the msg
	 */
	public String getMsg() {
		return msg;
	}

	/**
	 * @param msg
	 *            the msg to set
	 */
	public void setMsg(String msg) {
		this.msg = msg;
	}

	/**
	 * @return the profitModelHead
	 */

	public Operators getOperators() {
		return operators;
	}

	public void setOperators(Operators operators) {
		this.operators = operators;
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getIdd() {
		return idd;
	}

	public void setIdd(String idd) {
		this.idd = idd;
	}

	public AuditingItem getAuditing() {
		return auditing;
	}

	public void setAuditing(AuditingItem auditing) {
		this.auditing = auditing;
	}

	public SettingBean getSett() {
		return sett;
	}

	public void setSett(SettingBean sett) {
		this.sett = sett;
	}

	public ReviewSettingSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(ReviewSettingSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

}
